package test01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class RecvUDP {
	public static final int RECV_PORT = 4505;
	public static final int MAX_PACKET_SIZE = 10;
	
	public static void main(String str[]) {
		getNameAndIPLocalHost();
		recvUDP();
	}
	
	public static void getNameAndIPLocalHost() {
		InetAddress address;
		try {
			address = InetAddress.getLocalHost();
			System.out.println("===RecvUDP===");
			System.out.println("Local Host: " + address.getHostName() + ", " + address.getHostAddress());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
	
	  public static void recvUDP(){

		    DatagramSocket sock;
		    try {
		    	sock = new DatagramSocket(RECV_PORT);
		    	DatagramPacket packet = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);
		    	sock.receive(packet);
		    	int length = packet.getLength();
		    	byte[] data = packet.getData();
		    	InetAddress sourceAddr = packet.getAddress();
		    	String sourceHostName = sourceAddr.getHostName();
		    	String sourceHostAddr = sourceAddr.getHostAddress();
		    	System.out.println("packet received: ");
		    	System.out.println("---source name: " + sourceHostName);
		    	System.out.println("---source address: " + sourceHostAddr);
		    	System.out.println("---length: " + length);
		    	System.out.print("---data: ");
		    	for(int i=0; i<length; i++){
		    		System.out.print(data[i] + " ");
		    	}
		    	sock.close();
		    } catch (SocketException e) {
		    	e.printStackTrace();
		    } 
		    catch (IOException e) {
		    	e.printStackTrace();
		    }

		  }

}
